package controllers

import java.io.File

import dao._
import javax.inject.Inject
import models.Tables._
import play.api.mvc.{AbstractController, Action, ControllerComponents}
import utils.Utils

import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.Source
import scala.xml.Utility
import scala.xml.pull.{EvElemEnd, EvElemStart, EvEntityRef, EvText, XMLEvent, XMLEventReader}
import utils.Implicits._
import tool.Tool
import implicits.Implicits._

/**
 * Created by Administrator on 2019/8/14
 */
class DataInsertController @Inject()(cc: ControllerComponents, hmdbKeggInfoDao: HmdbKeggInfoDao,
                                     hmdbOtherNameKeggDao: HmdbOtherNameKeggDao, keggInfoDao: KeggInfoDao
                                    ) extends AbstractController(cc) {

  def insertOtherNameKegg = Action { implicit request =>
    val startTime = System.currentTimeMillis()

    val parent = new File("D:\\ip4m")
    val file = new File(parent, "other_name_kegg.txt")

    val rows = file.lines.notEmptyLines.mapOtherByColumns { columns =>
      val name = columns(0)
      val newName = Tool.cleanSpecialChr(columns(0))
      HmdbOtherNameKeggRow(newName, columns(1), Tool.cleanName(columns(0)))
    }.distinctBy(_.otherName)

    val rowsSize = rows.size
    val num = 5000
    var index = 0
    Utils.execFuture(hmdbOtherNameKeggDao.deleteAll)
    rows.grouped(num).foreach { x =>
      Utils.execFuture(hmdbOtherNameKeggDao.insertAll(x))
      index = index + 1
      val percent = if ((index * num * 100) / rowsSize >= 100) "100%" else (index * num * 100) / rowsSize + "%"
      println(percent + "\t" + Utils.getTime(startTime))
    }
    println("insert table successfully!" + Utils.getTime(startTime))
    Ok("success!")

  }

  def insertKeggInfo = Action { implicit request =>
    val startTime = System.currentTimeMillis()

    val parent = new File("D:\\ip4m")
    val file = new File(parent, "name_kegg.txt")

    val rows = file.lines.notEmptyLines.mapOtherByColumns { tmpColumns =>
      val columns = tmpColumns.padTo(4, "NA")
      HmdbKegginfoRow(columns(0), columns(1), columns(2), columns(3), Tool.cleanName(columns(0)))
    }

    val rowsSize = rows.size
    val num = 5000
    var index = 0
    Utils.execFuture(hmdbKeggInfoDao.deleteAll)
    rows.grouped(num).foreach { x =>
      Utils.execFuture(hmdbKeggInfoDao.insertAll(x))
      index = index + 1
      val percent = if ((index * num * 100) / rowsSize >= 100) "100%" else (index * num * 100) / rowsSize + "%"
      println(percent + "\t" + Utils.getTime(startTime))
    }
    println("insert table successfully!" + Utils.getTime(startTime))
    Ok("success!")

  }


}
